package com.evolvedb;

import java.util.regex.Pattern;

public class DottedVersion implements Comparable<DottedVersion> {

	String version;
	
	public String getVersion() {
		return version;
	}
	
	public DottedVersion(String version) throws InvalidVersionException {
		if (!Pattern.matches("(([0-9])+\\.?)+", version))
			throw new InvalidVersionException("Invalid dotted version: "+version+". Only numbers and periods are allowed.");
		this.version = version;
	}
	
	public int compareTo(DottedVersion o) {
		// Handle nulls
		if (getVersion() == null && o.getVersion() == null) {
			return 0;
		} else if (this.getVersion() == null) {
			return -1;
		} else if (o.getVersion() == null) {
			return 1;
		}
		
		String[] parts1 = getVersion().split("\\.");
		String[] parts2 = o.getVersion().split("\\.");
		
		// Compare each of my version parts to the passed in version parts
		for (int i=0; i<parts1.length; i++) {
			if (i >= parts2.length) {
				// Passed in Version is shorter in length
				// By my version sort rules that means I am a later version
				// e.g. 5.0.0 comes after 5.0 which comes after 5
				// (hopefully no one numbers like that in real life)
				return 1;
			} else {
				if (parts1[i].compareTo(parts2[i]) > 0) {
					// I'm a later version
					return 1;
				} else if (parts1[i].compareTo(parts2[i]) < 0) {
					// I'm an earlier version
					return -1;					
				}
			}
		}
		// Passed in Version is longer than me
		// That means I am an earlier version
		// e.g. 5 comes before 5.0 comes before 5.0.0
		if (parts1.length < parts2.length) {
			return -1;
		}
		
		// Otherwise we're exactly equal
		return 0;
	}
}